<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>积分商品管理 - MeetUp 管理后台</title>

    {% load static %}
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        /* 使用与 admin_index.html 相同的样式 */
        :root {
            --sidebar-width: 250px;
            --header-height: 60px;
            --primary-color: #FF8C42;
            --secondary-color: #FFB347;
            --accent-color: #FFD166;
            --light-color: #f8f9fa;
            --dark-color: #2D3047;
            --text-color: #333333;
            --bg-color: #FFF9F2;
        }

        .card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
            transition: transform 0.2s, box-shadow 0.2s;
            margin-bottom: 20px;
            overflow: hidden;
            background-color: white;
        }

        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
        }

        .stat-card {
            text-align: center;
            padding: 25px 15px;
            position: relative;
        }

        .stat-card i {
            font-size: 2.5rem;
            margin-bottom: 15px;
            color: var(--primary-color);
            background: rgba(255, 140, 66, 0.1);
            width: 70px;
            height: 70px;
            line-height: 70px;
            border-radius: 50%;
            display: inline-block;
        }

        .stat-card .number {
            font-size: 2.2rem;
            font-weight: bold;
            color: var(--dark-color);
            margin: 10px 0;
        }

        .badge-active { background-color: #28a745; }
        .badge-inactive { background-color: #6c757d; }
        .badge-sold-out { background-color: #dc3545; }
        .badge-virtual { background-color: #17a2b8; }
        .badge-physical { background-color: #007bff; }
        .badge-coupon { background-color: #6f42c1; }
    </style>
</head>
<body>
    <!-- 侧边栏和顶部导航栏与 admin_index.html 相同 -->
    <!-- 这里省略重复的侧边栏和导航栏代码 -->

    <!-- 主内容区 -->
    <div id="content">
        <nav class="navbar navbar-expand navbar-light bg-white">
            <div class="container-fluid">
                <button type="button" id="sidebarCollapse" class="btn btn-primary">
                    <i class="bi bi-list"></i>
                </button>
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown">
                            <i class="bi bi-person-circle"></i> {{ request.user.username }}
                        </a>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="/user/person_center/"><i class="bi bi-person"></i> 个人资料</a></li>
                            <li><a class="dropdown-item" href="#"><i class="bi bi-gear"></i> 设置</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="/user/logout/"><i class="bi bi-box-arrow-right"></i> 退出</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </nav>

        <div class="container-fluid p-4">
            <h2 class="mb-4">积分商品管理</h2>

            <!-- 统计卡片 -->
            <div class="row mb-4">
                <div class="col-md-3">
                    <div class="card stat-card">
                        <i class="bi bi-box-seam"></i>
                        <div class="number">{{ points_stats.total_products }}</div>
                        <div class="label">总商品数</div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card stat-card">
                        <i class="bi bi-check-circle"></i>
                        <div class="number">{{ points_stats.active_products }}</div>
                        <div class="label">上架商品</div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card stat-card">
                        <i class="bi bi-arrow-left-right"></i>
                        <div class="number">{{ points_stats.total_exchanges }}</div>
                        <div class="label">总兑换数</div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card stat-card">
                        <i class="bi bi-clock"></i>
                        <div class="number">{{ points_stats.pending_exchanges }}</div>
                        <div class="label">待处理兑换</div>
                    </div>
                </div>
            </div>

            <!-- 搜索和操作栏 -->
            <div class="card">
                <div class="card-body">
                    <div class="row g-3">
                        <div class="col-md-8">
                            <form class="row g-2" method="get">
                                <div class="col-md-4">
                                    <input type="text" class="form-control" name="search" value="{{ search_query }}" placeholder="搜索商品名称...">
                                </div>
                                <div class="col-md-3">
                                    <select class="form-select" name="status">
                                        <option value="">所有状态</option>
                                        {% for status_value, status_name in status_choices %}
                                            <option value="{{ status_value }}" {% if product_status == status_value %}selected{% endif %}>
                                                {{ status_name }}
                                            </option>
                                        {% endfor %}
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <select class="form-select" name="category">
                                        <option value="">所有分类</option>
                                        {% for category_value, category_name in category_choices %}
                                            <option value="{{ category_value }}" {% if product_category == category_value %}selected{% endif %}>
                                                {{ category_name }}
                                            </option>
                                        {% endfor %}
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <button type="submit" class="btn btn-primary w-100">搜索</button>
                                </div>
                            </form>
                        </div>
                        <div class="col-md-4 text-end">
                            <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#addProductModal">
                                <i class="bi bi-plus-circle"></i> 添加商品
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 商品列表 -->
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="card-title mb-0">商品列表</h5>
                    <span class="text-muted">共 {{ page_obj.paginator.count }} 个商品</span>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>商品图片</th>
                                    <th>商品名称</th>
                                    <th>分类</th>
                                    <th>所需积分</th>
                                    <th>库存</th>
                                    <th>兑换次数</th>
                                    <th>状态</th>
                                    <th>创建时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for product in page_obj %}
                                <tr>
                                    <td>
                                        {% if product.image %}
                                            <img src="{{ product.image.url }}" alt="{{ product.name }}" style="width: 50px; height: 50px; object-fit: cover; border-radius: 8px;">
                                        {% else %}
                                            <div style="width: 50px; height: 50px; background: #f8f9fa; border-radius: 8px; display: flex; align-items: center; justify-content: center;">
                                                <i class="bi bi-image text-muted"></i>
                                            </div>
                                        {% endif %}
                                    </td>
                                    <td>
                                        <strong>{{ product.name }}</strong>
                                        {% if product.original_price %}
                                            <br><small class="text-muted">原价: ¥{{ product.original_price }}</small>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if product.category == 'virtual' %}
                                            <span class="badge badge-virtual">虚拟商品</span>
                                        {% elif product.category == 'physical' %}
                                            <span class="badge badge-physical">实物商品</span>
                                        {% elif product.category == 'coupon' %}
                                            <span class="badge badge-coupon">优惠券</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        <span class="fw-bold text-warning">{{ product.points_required }}</span> 积分
                                    </td>
                                    <td>{{ product.stock }}</td>
                                    <td>{{ product.exchange_count }}</td>
                                    <td>
                                        {% if product.status == 'active' %}
                                            <span class="badge badge-active">上架</span>
                                        {% elif product.status == 'inactive' %}
                                            <span class="badge badge-inactive">下架</span>
                                        {% elif product.status == 'sold_out' %}
                                            <span class="badge badge-sold-out">售罄</span>
                                        {% endif %}
                                    </td>
                                    <td>{{ product.created_at|date:"Y-m-d" }}</td>
                                    <td>
                                        <div class="btn-group btn-group-sm">
                                            <button type="button" class="btn btn-outline-primary edit-product-btn"
                                                    data-product-id="{{ product.id }}"
                                                    data-product-name="{{ product.name }}"
                                                    data-product-description="{{ product.description }}"
                                                    data-product-category="{{ product.category }}"
                                                    data-product-points="{{ product.points_required }}"
                                                    data-product-stock="{{ product.stock }}"
                                                    data-product-price="{{ product.original_price|default:'' }}"
                                                    data-product-status="{{ product.status }}">
                                                <i class="bi bi-pencil"></i> 编辑
                                            </button>
                                            <button type="button" class="btn btn-outline-danger delete-product-btn"
                                                    data-product-id="{{ product.id }}"
                                                    data-product-name="{{ product.name }}">
                                                <i class="bi bi-trash"></i> 删除
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                {% empty %}
                                <tr>
                                    <td colspan="9" class="text-center py-4">
                                        <i class="bi bi-inbox display-4 text-muted"></i>
                                        <p class="mt-2 text-muted">暂无商品</p>
                                    </td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>

                    <!-- 分页 -->
                    {% if page_obj.has_other_pages %}
                    <nav>
                        <ul class="pagination justify-content-center">
                            {% if page_obj.has_previous %}
                            <li class="page-item">
                                <a class="page-link" href="?page={{ page_obj.previous_page_number }}{% if search_query %}&search={{ search_query }}{% endif %}{% if product_status %}&status={{ product_status }}{% endif %}{% if product_category %}&category={{ product_category }}{% endif %}">上一页</a>
                            </li>
                            {% endif %}

                            {% for i in page_obj.paginator.page_range %}
                            <li class="page-item {% if page_obj.number == i %}active{% endif %}">
                                <a class="page-link" href="?page={{ i }}{% if search_query %}&search={{ search_query }}{% endif %}{% if product_status %}&status={{ product_status }}{% endif %}{% if product_category %}&category={{ product_category }}{% endif %}">{{ i }}</a>
                            </li>
                            {% endfor %}

                            {% if page_obj.has_next %}
                            <li class="page-item">
                                <a class="page-link" href="?page={{ page_obj.next_page_number }}{% if search_query %}&search={{ search_query }}{% endif %}{% if product_status %}&status={{ product_status }}{% endif %}{% if product_category %}&category={{ product_category }}{% endif %}">下一页</a>
                            </li>
                            {% endif %}
                        </ul>
                    </nav>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>

    <!-- 添加商品模态框 -->
    <div class="modal fade" id="addProductModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加积分商品</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="addProductForm" enctype="multipart/form-data">
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="productName" class="form-label">商品名称 <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="productName" name="name" required maxlength="100" placeholder="请输入商品名称">
                                </div>
                                <div class="mb-3">
                                    <label for="productCategory" class="form-label">商品分类 <span class="text-danger">*</span></label>
                                    <select class="form-select" id="productCategory" name="category" required>
                                        {% for category_value, category_name in category_choices %}
                                            <option value="{{ category_value }}">{{ category_name }}</option>
                                        {% endfor %}
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label for="productPoints" class="form-label">所需积分 <span class="text-danger">*</span></label>
                                    <input type="number" class="form-control" id="productPoints" name="points_required" required min="1" placeholder="请输入所需积分">
                                </div>
                                <div class="mb-3">
                                    <label for="productStock" class="form-label">库存数量</label>
                                    <input type="number" class="form-control" id="productStock" name="stock" value="0" min="0" placeholder="请输入库存数量">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="productDescription" class="form-label">商品描述</label>
                                    <textarea class="form-control" id="productDescription" name="description" rows="4" placeholder="请输入商品描述"></textarea>
                                </div>
                                <div class="mb-3">
                                    <label for="productPrice" class="form-label">原价（元）</label>
                                    <input type="number" class="form-control" id="productPrice" name="original_price" step="0.01" min="0" placeholder="请输入原价">
                                </div>
                                <div class="mb-3">
                                    <label for="productStatus" class="form-label">商品状态</label>
                                    <select class="form-select" id="productStatus" name="status">
                                        {% for status_value, status_name in status_choices %}
                                            <option value="{{ status_value }}">{{ status_name }}</option>
                                        {% endfor %}
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label for="productImage" class="form-label">商品图片</label>
                                    <input type="file" class="form-control" id="productImage" name="image" accept="image/*">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="submit" class="btn btn-primary">添加商品</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 编辑商品模态框 -->
    <div class="modal fade" id="editProductModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">编辑积分商品</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="editProductForm" enctype="multipart/form-data">
                    <input type="hidden" id="editProductId" name="product_id">
                    <div class="modal-body">
                        <!-- 与添加商品模态框相同的表单结构 -->
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="editProductName" class="form-label">商品名称</label>
                                    <input type="text" class="form-control" id="editProductName" name="name" required>
                                </div>
                                <div class="mb-3">
                                    <label for="editProductCategory" class="form-label">商品分类</label>
                                    <select class="form-select" id="editProductCategory" name="category" required>
                                        {% for category_value, category_name in category_choices %}
                                            <option value="{{ category_value }}">{{ category_name }}</option>
                                        {% endfor %}
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label for="editProductPoints" class="form-label">所需积分</label>
                                    <input type="number" class="form-control" id="editProductPoints" name="points_required" required>
                                </div>
                                <div class="mb-3">
                                    <label for="editProductStock" class="form-label">库存数量</label>
                                    <input type="number" class="form-control" id="editProductStock" name="stock" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="editProductDescription" class="form-label">商品描述</label>
                                    <textarea class="form-control" id="editProductDescription" name="description" rows="4"></textarea>
                                </div>
                                <div class="mb-3">
                                    <label for="editProductPrice" class="form-label">原价（元）</label>
                                    <input type="number" class="form-control" id="editProductPrice" name="original_price" step="0.01">
                                </div>
                                <div class="mb-3">
                                    <label for="editProductStatus" class="form-label">商品状态</label>
                                    <select class="form-select" id="editProductStatus" name="status">
                                        {% for status_value, status_name in status_choices %}
                                            <option value="{{ status_value }}">{{ status_name }}</option>
                                        {% endfor %}
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label for="editProductImage" class="form-label">商品图片</label>
                                    <input type="file" class="form-control" id="editProductImage" name="image" accept="image/*">
                                    <div class="form-text">如不选择新图片，将保留原图片</div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="submit" class="btn btn-primary">保存修改</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 删除商品确认模态框 -->
    <div class="modal fade" id="deleteProductModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">删除商品</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="alert alert-danger">
                        <i class="bi bi-exclamation-triangle"></i>
                        <strong>警告：此操作不可逆！</strong>
                    </div>
                    <p>确定要删除商品 <strong id="deleteProductName"></strong> 吗？</p>
                    <p class="text-muted">如果该商品已有兑换记录，则无法删除。</p>
                    <input type="hidden" id="deleteProductId">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" id="confirmDeleteProductBtn">确认删除</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 编辑商品按钮
            document.addEventListener('click', function(e) {
                if (e.target.closest('.edit-product-btn')) {
                    const button = e.target.closest('.edit-product-btn');
                    const productId = button.dataset.productId;
                    const productName = button.dataset.productName;
                    const productDescription = button.dataset.productDescription;
                    const productCategory = button.dataset.productCategory;
                    const productPoints = button.dataset.productPoints;
                    const productStock = button.dataset.productStock;
                    const productPrice = button.dataset.productPrice;
                    const productStatus = button.dataset.productStatus;

                    document.getElementById('editProductId').value = productId;
                    document.getElementById('editProductName').value = productName;
                    document.getElementById('editProductDescription').value = productDescription;
                    document.getElementById('editProductCategory').value = productCategory;
                    document.getElementById('editProductPoints').value = productPoints;
                    document.getElementById('editProductStock').value = productStock;
                    document.getElementById('editProductPrice').value = productPrice;
                    document.getElementById('editProductStatus').value = productStatus;

                    const modal = new bootstrap.Modal(document.getElementById('editProductModal'));
                    modal.show();
                }

                // 删除商品按钮
                if (e.target.closest('.delete-product-btn')) {
                    const button = e.target.closest('.delete-product-btn');
                    const productId = button.dataset.productId;
                    const productName = button.dataset.productName;

                    document.getElementById('deleteProductId').value = productId;
                    document.getElementById('deleteProductName').textContent = productName;

                    const modal = new bootstrap.Modal(document.getElementById('deleteProductModal'));
                    modal.show();
                }
            });

            // 添加商品表单提交
            document.getElementById('addProductForm').addEventListener('submit', function(e) {
                e.preventDefault();
                addProduct();
            });

            // 编辑商品表单提交
            document.getElementById('editProductForm').addEventListener('submit', function(e) {
                e.preventDefault();
                const productId = document.getElementById('editProductId').value;
                updateProduct(productId);
            });

            // 确认删除商品
            document.getElementById('confirmDeleteProductBtn').addEventListener('click', function() {
                const productId = document.getElementById('deleteProductId').value;
                deleteProduct(productId);
            });
        });

        function addProduct() {
            const formData = new FormData(document.getElementById('addProductForm'));

            fetch('/user/admin/points/product/add/', {
                method: 'POST',
                headers: {
                    'X-CSRFToken': getCookie('csrftoken'),
                },
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    bootstrap.Modal.getInstance(document.getElementById('addProductModal')).hide();
                    location.reload();
                } else {
                    alert('操作失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('操作失败: ' + error.message);
            });
        }

        function updateProduct(productId) {
            const formData = new FormData(document.getElementById('editProductForm'));

            fetch(`/user/admin/points/product/${productId}/update/`, {
                method: 'POST',
                headers: {
                    'X-CSRFToken': getCookie('csrftoken'),
                },
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    bootstrap.Modal.getInstance(document.getElementById('editProductModal')).hide();
                    location.reload();
                } else {
                    alert('操作失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('操作失败: ' + error.message);
            });
        }

        function deleteProduct(productId) {
            fetch(`/user/admin/points/product/${productId}/delete/`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-CSRFToken': getCookie('csrftoken'),
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    bootstrap.Modal.getInstance(document.getElementById('deleteProductModal')).hide();
                    location.reload();
                } else {
                    alert('操作失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('操作失败: ' + error.message);
            });
        }

        function getCookie(name) {
            let cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                const cookies = document.cookie.split(';');
                for (let i = 0; i < cookies.length; i++) {
                    const cookie = cookies[i].trim();
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
    </script>
</body>
</html>